<script lang="ts" setup>
import { SelectOption, useMessage } from 'naive-ui'
import { onMounted, reactive } from 'vue'
import { getAll } from '@tauri-apps/api/window'
import { AiService, CommandAiConfig, new_command_ai_config } from '@/models/commands/command_ai_config.ts'
import { invoke_proxy } from '@/functions/invoke.ts'
import { BackendResponse } from '@/runtime/response.ts'
import { BACKEND_CODE_CONFIG_NOT_EXISTS, BACKEND_CODE_OK } from '@/runtime/code.ts'
import { use_ui_setting } from '@/state/pinia.ts'
import { CommandSearchConfig, new_command_search_config } from '@/models/commands/command_search_config.ts'

const ali_yun_models: SelectOption[] = [
    { label: '通义千问 - Turbo', value: 'QWenTurbo' },
    { label: '通义千问 - Plus', value: 'QWenPlus' },
    { label: '通义千问 - Max', value: 'QWenMax' },
    { label: '通义千问开源系列 - 1.8B - Chat', value: 'QWen18BChat' },
    { label: '通义千问开源系列 - 7B - Chat', value: 'QWen7BChat' },
    { label: '通义千问开源系列 - 14B - Chat', value: 'QWen14BChat' },
    { label: '通义千问开源系列 - 72B - Chat', value: 'QWen72BChat' },
    { label: 'LLaMa2 - 7B', value: 'LLaMa27B' },
    { label: 'LLaMa2 - 13B', value: 'LLaMa213B' },
]

const ui_setting = use_ui_setting()

declare type State = { basic: { send_mode: string; message_cnt: number; default_command: string; default_search_engine: string }; ai: CommandAiConfig; search: CommandSearchConfig; messages: number; search_history_append_to_history: boolean }
const state = reactive<State>({ basic: { send_mode: 'Enter', message_cnt: 100, default_command: 'search', default_search_engine: 'Google' }, ai: new_command_ai_config(), search: new_command_search_config(), messages: 100, search_history_append_to_history: false })

onMounted(async () => {
    window.Message = useMessage()

    // 监听键盘释放事件
    document.onkeydown = async (event: KeyboardEvent) => {
        if ('w' === event.key.toLowerCase() && event.metaKey) {
            event.preventDefault()

            const windows = getAll()
            for (const window of windows) {
                if ('setting' === window.label) {
                    await window.close()
                }
            }
        }
    }

    {
        state.basic.send_mode = ui_setting.send_mode
        state.basic.default_command = ui_setting.default_command
        state.basic.default_search_engine = ui_setting.default_search_engine
    }

    {
        // 加载配置
        const response = await invoke_proxy<BackendResponse<string>>('invoke_get_setting', { name: 'command.ai.config' })
        if (BACKEND_CODE_OK !== response.code && BACKEND_CODE_CONFIG_NOT_EXISTS !== response.code) {
            window.Message.error(response.message)

            return
        }

        if (response.data) {
            state.ai = Object.assign(state.ai, JSON.parse(response.data) as CommandAiConfig)
        }
    }

    {
        // 加载配置
        const response = await invoke_proxy<BackendResponse<string>>('invoke_get_setting', { name: 'command.search.config' })
        if (BACKEND_CODE_OK !== response.code && BACKEND_CODE_CONFIG_NOT_EXISTS !== response.code) {
            window.Message.error(response.message)

            return
        }

        if (response.data) {
            state.search = Object.assign(state.search, JSON.parse(response.data) as CommandSearchConfig)
        }
    }

    {
        // 加载配置
        const response = await invoke_proxy<BackendResponse<string>>('invoke_get_setting', { name: 'system.message.length' })
        if (BACKEND_CODE_OK !== response.code && BACKEND_CODE_CONFIG_NOT_EXISTS !== response.code) {
            window.Message.error(response.message)

            return
        }

        if (response.data) {
            state.basic.message_cnt = parseInt(response.data)
        }
    }

    {
        // 加载配置
        const response = await invoke_proxy<BackendResponse<string>>('invoke_get_setting', { name: 'command.search.append_to_history' })
        if (BACKEND_CODE_OK !== response.code && BACKEND_CODE_CONFIG_NOT_EXISTS !== response.code) {
            window.Message.error(response.message)

            return
        }

        if (response.data) {
            state.search_history_append_to_history = 'Y' === response.data
        }
    }
})

async function save_command_ai_config(): Promise<void> {
    if ('AliYun' === state.ai.service && '' === state.ai.ali_yun_api_config.token) {
        window.Message.error('使用阿里云服务时，必须填写阿里云灵积模型的API KEY字符串')

        return
    }

    const response = await invoke_proxy<BackendResponse<any>>('invoke_set_setting', { name: 'command.ai.config', value: JSON.stringify(state.ai) })
    if (BACKEND_CODE_OK !== response.code) {
        window.Message.error(response.message)

        return
    }

    window.Message.success('保存配置成功')
}

async function save_command_search_config(): Promise<void> {
    const response = await invoke_proxy<BackendResponse<any>>('invoke_set_setting', { name: 'command.search.config', value: JSON.stringify(state.search) })
    if (BACKEND_CODE_OK !== response.code) {
        window.Message.error(response.message)

        return
    }

    window.Message.success('保存配置成功')
}

async function save_basic_setting(): Promise<void> {
    ui_setting.set_send_mode(state.basic.send_mode)
    ui_setting.set_default_command(state.basic.default_command)
    ui_setting.set_default_search_engine(state.basic.default_search_engine)

    const response = await invoke_proxy<BackendResponse<any>>('invoke_set_setting', { name: 'system.message.length', value: state.basic.message_cnt.toString() })
    if (BACKEND_CODE_OK !== response.code) {
        window.Message.error(response.message)

        return
    }

    window.Message.success('保存配置成功')
}
</script>

<template>
    <n-space :wrap="false" :wrap-item="false" vertical>
        <div class="title" data-tauri-drag-region>Magic Box 配置面板</div>
        <n-collapse accordion default-expanded-names="1">
            <n-collapse-item name="system-setting" title="Magic Box基础配置">
                <n-space :wrap="false" :wrap-item="false" vertical>
                    <n-space :wrap="false" :wrap-item="false" align="center">
                        <div>
                            <n-input-group>
                                <n-input-group-label size="small">消息发送操作模式</n-input-group-label>
                                <n-radio-group v-model:value="state.basic.send_mode" size="small">
                                    <n-radio-button value="Enter">Enter</n-radio-button>
                                    <n-radio-button value="Ctrl+Enter">Ctrl + Enter</n-radio-button>
                                    <n-radio-button value="Meta+Enter">Meta + Enter</n-radio-button>
                                </n-radio-group>
                            </n-input-group>
                        </div>
                        <div>
                            <n-input-group>
                                <n-input-group-label size="small">消息列表长度</n-input-group-label>
                                <n-input-number v-model:value="state.basic.message_cnt" max="100" min="10" size="small" style="width: 85px"></n-input-number>
                            </n-input-group>
                        </div>
                    </n-space>
                    <n-space :wrap="false" :wrap-item="false" align="center">
                        <div class="max-flex-width">
                            <n-input-group class="max-width">
                                <n-input-group-label size="small">默认调用的命令</n-input-group-label>
                                <n-select
                                    v-model:value="state.basic.default_command"
                                    :options="[
                                        { label: 'AI', value: 'ai' },
                                        { label: 'Search', value: 'search' },
                                    ]"
                                    class="max-width"
                                    size="small"
                                >
                                    >
                                </n-select>
                            </n-input-group>
                        </div>
                        <div v-if="'search' === ui_setting.default_command">
                            <n-input-group>
                                <n-input-group-label size="small">默认的搜索引擎</n-input-group-label>
                                <n-radio-group v-model:value="state.basic.default_search_engine" size="small">
                                    <n-radio-button value="Google">谷歌</n-radio-button>
                                    <n-radio-button value="Bing">必应</n-radio-button>
                                    <n-radio-button value="Baidu">百度</n-radio-button>
                                </n-radio-group>
                            </n-input-group>
                        </div>
                    </n-space>
                    <n-button class="max-width" size="small" type="info" @click="save_basic_setting">保存配置</n-button>
                </n-space>
            </n-collapse-item>
            <n-collapse-item name="ai-setting" title="命令配置: AI">
                <n-space :wrap="false" :wrap-item="false" vertical>
                    <n-space :wrap="false" :wrap-item="false" align="center">
                        <div>
                            <n-input-group>
                                <n-input-group-label size="small">是否加入命令历史</n-input-group-label>
                                <n-radio-group v-model:value="state.ai.basic_command_setting.append_to_history" size="small">
                                    <n-radio-button :value="true">是</n-radio-button>
                                    <n-radio-button :value="false">否</n-radio-button>
                                </n-radio-group>
                            </n-input-group>
                        </div>
                    </n-space>
                    <n-space :wrap="false" :wrap-item="false" align="center">
                        <div class="max-flex-width">
                            <n-input-group>
                                <n-input-group-label size="small">选择AI服务商</n-input-group-label>
                                <n-select :options="[{ label: '灵积模型 - 阿里云', value: AiService.AliYun }]" :value="state.ai.service" size="small"></n-select>
                            </n-input-group>
                        </div>
                        <div>
                            <n-input-group>
                                <n-input-group-label size="small">携带会话上下文</n-input-group-label>
                                <n-radio-group v-model:value="state.ai.post_context" size="small">
                                    <n-radio-button :value="true" size="small">是</n-radio-button>
                                    <n-radio-button :value="false" size="small">否</n-radio-button>
                                </n-radio-group>
                            </n-input-group>
                        </div>
                        <div>
                            <n-input-group>
                                <n-input-group-label size="small">会话上下文数量</n-input-group-label>
                                <n-input-number v-model:value="state.ai.post_context_cnt" max="999" min="1" size="small"></n-input-number>
                            </n-input-group>
                        </div>
                    </n-space>
                    <template v-if="'AliYun' === state.ai.service">
                        <n-space :wrap="false" :wrap-item="false" align="center">
                            <div class="max-flex-width">
                                <n-input-group>
                                    <n-input-group-label size="small">选择阿里云AI模型</n-input-group-label>
                                    <n-select v-model:value="state.ai.ali_yun_api_config.model" :options="ali_yun_models" size="small"></n-select>
                                </n-input-group>
                            </div>
                            <div>
                                <n-input-group>
                                    <n-input-group-label size="small">启用联网搜索</n-input-group-label>
                                    <n-radio-group v-model:value="state.ai.ali_yun_api_config.enable_search" size="small">
                                        <n-radio-button :value="true" size="small">启用</n-radio-button>
                                        <n-radio-button :value="false" size="small">禁用</n-radio-button>
                                    </n-radio-group>
                                </n-input-group>
                            </div>
                        </n-space>
                        <n-space :wrap="false" :wrap-item="false" align="center">
                            <n-input-group class="max-flex-width">
                                <n-input-group-label size="small">阿里云API KEY</n-input-group-label>
                                <n-input v-model:value="state.ai.ali_yun_api_config.token" :show-password-toggle="false" placeholder="输入阿里云灵积模型的API KEY字符串，此项为必填项" show-password-on="click" size="small" type="password"></n-input>
                            </n-input-group>
                        </n-space>
                    </template>
                    <n-button class="max-width" size="small" type="info" @click="save_command_ai_config">保存配置</n-button>
                </n-space>
            </n-collapse-item>
            <n-collapse-item name="search-setting" title="命令配置: SEARCH">
                <n-space :wrap="false" :wrap-item="false" vertical>
                    <n-space :wrap="false" :wrap-item="false" align="center">
                        <div>
                            <n-input-group>
                                <n-input-group-label size="small">是否加入命令历史</n-input-group-label>
                                <n-radio-group v-model:value="state.search.basic_command_setting.append_to_history" size="small">
                                    <n-radio-button :value="true">是</n-radio-button>
                                    <n-radio-button :value="false">否</n-radio-button>
                                </n-radio-group>
                            </n-input-group>
                        </div>
                        <div>
                            <n-input-group>
                                <n-input-group-label size="small">是否自动关闭窗口</n-input-group-label>
                                <n-radio-group v-model:value="state.search.basic_command_setting.autoclose_window_after_execute" size="small">
                                    <n-radio-button :value="true">是</n-radio-button>
                                    <n-radio-button :value="false">否</n-radio-button>
                                </n-radio-group>
                            </n-input-group>
                        </div>
                    </n-space>
                    <n-button class="max-width" size="small" type="info" @click="save_command_search_config">保存配置</n-button>
                </n-space>
            </n-collapse-item>
        </n-collapse>
    </n-space>
</template>

<style lang="scss" scoped>
@import '@/assets/scss/variables';

.title {
    font-size: 24px;
    line-height: 2;
    cursor: default;
    text-align: center;
}

.n-collapse-item {
    :deep(.n-collapse-item__header-main) {
        line-height: 2;
        font-size: 16px;
        background-color: $color-message-background;
    }
}
</style>
